package karma.pool.pool;

import karma.pool.log.Recorder;

import static karma.pool.util.clock.ClockFactory.currentTime;
import static karma.pool.util.clock.ClockFactory.elapsedNanos;

/**
 * A class that delegates to a MetricsTracker implementation.  The use of a connection
 * allows us to use the NopMetricsTrackerDelegate when log are disabled, which in
 * turn allows the JIT to completely optimize away to callsites to record log.
 */
class RecorderDelegateImpl implements RecorderDelegate {
   final Recorder recorder;

   RecorderDelegateImpl(Recorder recorder) {
      this.recorder = recorder;
   }

   @Override
   public void recordConnectionUsage(final PoolEntry poolEntry) {
      recorder.recordConnectionUsageMillis(poolEntry.getMillisSinceBorrowed());
   }

   @Override
   public void recordConnectionCreated(long connectionCreatedMillis) {
      recorder.recordConnectionCreatedMillis(connectionCreatedMillis);
   }

   @Override
   public void recordBorrowTimeoutStats(long startTime) {
      recorder.recordConnectionAcquiredNanos(elapsedNanos(startTime));
   }

   @Override
   public void recordBorrowStats(final PoolEntry poolEntry, final long startTime) {
      final long now = currentTime();
      poolEntry.lastBorrowed = now;
      recorder.recordConnectionAcquiredNanos(elapsedNanos(startTime, now));
   }

   @Override
   public void recordConnectionTimeout() {
      recorder.recordConnectionTimeout();
   }

   @Override
   public void close() {
      recorder.close();
   }
}
